<template>
  <a-layout>
    <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
      <h3 v-if="level1.length === 0">对不起，找不到相关文档！</h3>
      <a-row>
        <a-col :span="3" >
          <a-tree style="margin-left: 10px"
              v-if="level1.length > 0"
              :tree-data="level1"
              @select="onSelect"
              :autoExpandParent="true"
              :defaultExpandAll="true"
              :fieldNames="{title: 'name', key: 'id', children: 'children'}"
              v-model:selectedKeys="defaultSelectedKeys"
          >
          </a-tree>
        </a-col>
        <a-col :span="1">
          <a-divider type="vertical" style="height: 100%;width: 2px; background-color: #dedddd" />
        </a-col>
        <a-col :span="20">
          <div>
            <h2>{{doc.name}}</h2>
            <div>
              <span>阅读数：{{doc.viewCount}}&nbsp;</span>
              <span>点赞数：{{doc.voteCount}}</span>
            </div>
            <a-divider style="height: 2px; background-color: #9999cc"/>
          </div>
          <div class="wangeditor" :innerHTML="html"></div>
          <div class="vote-div">
              <a-button v-if="!isNotVote" type="primary" shape="round" :size="'large'" @click="vote">
                <template #icon>
                  <LikeOutlined />
                </template>
                &nbsp;点赞：{{doc.voteCount}}
              </a-button>
            <a-button v-if="isNotVote" style="background: #bbe5fd;border-color: #bbe5fd" type="primary" shape="round" :size="'large'" @click="vote">
              <template #icon>
                <LikeOutlined />
              </template>
              &nbsp;点赞：{{doc.voteCount}}
            </a-button>
          </div>
        </a-col>
      </a-row>
    </a-layout-content>
  </a-layout>
</template>

<script lang="ts">
import {defineComponent, onMounted, ref, createVNode, computed} from 'vue';
import axios from 'axios';
import {message} from 'ant-design-vue';
import {Tool} from "@/util/tool";
import {useRoute} from "vue-router";
import store from "@/store";

export default defineComponent({
  name: 'Doc',
  setup() {
    //登陆后保存用户信息
    const user = computed(() => {
      return store.state.user;
    });
    const route = useRoute();
    const docs = ref();
    const html = ref();
    const expanded = ref(true)
    const defaultSelectedKeys = ref();
    defaultSelectedKeys.value = [];
    const isNotVote = ref(true);
    // 当前选中的文档
    const doc = ref();
    doc.value = {};

    /**
     * 一级文档树，children属性就是二级文档
     * [{
     *   id: "",
     *   name: "",
     *   children: [{
     *     id: "",
     *     name: "",
     *   }]
     * }]
     */
    const level1 = ref([{
      id: null,
      name: null,
      children: []
    }]); // 一级文档树，children属性就是二级文档
    level1.value = [];
    //BUG退出登录再刷新，再登录user是空对象必须再刷新
    const voteUser = ref({
      userId: user.value.id,
      infoId: 0,
      operation: ""
    });

    const setVoteUser = () => {
      let u = sessionStorage.getItem('USRE');
      if (Tool.isEmpty(voteUser.value.userId) && u != null){
        voteUser.value.userId = JSON.parse(u).id
      } else {
        voteUser.value.userId = user.value.id;
      }
      voteUser.value.infoId = doc.value.id;
      voteUser.value.operation = isNotVote.value ? "add" : "subtract";
    }
    //判断用户是否点赞过
    const isVoted = () => {
      console.log("vote============="+doc.value.id);
      // voteUser.value.userId = user.value.id;
      // voteUser.value.infoId = doc.value.id;
      setVoteUser();
      axios.post('/vote/isVoted', voteUser.value).then((response) => {
        const data = response.data;
        if (data.success) {
          isNotVote.value = data.content;
        } else {
          message.error(data.message);
        }
      });
    }

    /**
     * 内容查询
     **/
    const handleQueryContent = (id: number) => {
      axios.get("/doc/find-content/" + id).then((response) => {
        const data = response.data;
        if (data.success) {
          html.value = data.content;
          isVoted();
        } else {
          message.error(data.message);
        }
      });
    };

    /**
     * 数据查询
     **/
    const handleQuery = () => {
      axios.get("/doc/all/" + route.query.ebookId).then((response) => {
        const data = response.data;
        if (data.success) {
          docs.value = data.content;

          level1.value = [];
          level1.value = Tool.array2Tree(docs.value, 0);

          if (Tool.isNotEmpty(level1)) {
            defaultSelectedKeys.value[0] = level1.value[0].id;
            handleQueryContent(Number(level1.value[0].id));
            // 初始显示文档信息
            doc.value = level1.value[0];
            isVoted();
          }
        } else {
          message.error(data.message);
        }
      });
    };

    const onSelect = (selectedKeys: any, e: any) => {
      console.log('selected', selectedKeys, e);
      console.log("selectedKeys========"+JSON.stringify(e.selectedNodes[0]))
      console.log("selectedKeys========"+e.node)
      if (Tool.isNotEmpty(selectedKeys)) {
        // 选中某一节点时，加载该节点的文档信息
        doc.value = e.selectedNodes[0];
        // 加载内容
        handleQueryContent(doc.value.id);
      }
    };

    // 点赞
    //用于判断用户是否点赞过，留作后续BUG

    const vote = () => {
      // voteUser.value.operation = isNotVote.value ? "add" : "subtract";
      // console.log("vote============="+doc.value.id);
      // voteUser.value.infoId = doc.value.id;
      setVoteUser();
      if (Tool.isNotEmpty(user.value)) {
        axios.post('/doc/vote', voteUser.value).then((response) => {
          const data = response.data;
          if (data.success) {
            isNotVote.value ? doc.value.voteCount++ : doc.value.voteCount--;
            isNotVote.value = !isNotVote.value;
            // message.success("点赞成功");
          } else {
            message.error(data.message);
          }
        });
      } else {
        message.info("请先登录");
      }
    };


    onMounted(() => {
      console.log("doc-------------onMounted");
      handleQuery();


    });

    return {
      level1,
      html,
      expanded,
      onSelect,
      defaultSelectedKeys,
      doc,
      vote,
      isNotVote,
      user,
      voteUser
    }
  }
});
</script>

<style>
/* wangeditor默认样式, 参照: http://www.wangeditor.com/doc/pages/02-%E5%86%85%E5%AE%B9%E5%A4%84%E7%90%86/03-%E8%8E%B7%E5%8F%96html.html */
/* table 样式 */
.wangeditor table {
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
}
.wangeditor table td,
.wangeditor table th {
  border-bottom: 1px solid #ccc;
  border-right: 1px solid #ccc;
  padding: 3px 5px;
}
.wangeditor table th {
  border-bottom: 2px solid #ccc;
  text-align: center;
}

/* blockquote 样式 */
.wangeditor blockquote {
  display: block;
  border-left: 8px solid #d0e5f2;
  padding: 5px 10px;
  margin: 10px 0;
  line-height: 1.4;
  font-size: 100%;
  background-color: #f1f1f1;
}

/* code 样式 */
.wangeditor code {
  display: inline-block;
  *display: inline;
  *zoom: 1;
  background-color: #f1f1f1;
  border-radius: 3px;
  padding: 3px 5px;
  margin: 0 3px;
}
.wangeditor pre code {
  display: block;
}

/* ul ol 样式 */
.wangeditor ul, ol {
  margin: 10px 0 10px 20px;
}

/* 和antdv p冲突，覆盖掉 */
.wangeditor blockquote p {
  font-family:"YouYuan";
  margin: 20px 10px !important;
  font-size: 16px !important;
  font-weight:600;
}

/* 点赞 */
.vote-div {
  padding: 15px;
  text-align: center;
}

/* 图片自适应 */
.wangeditor img {
  max-width: 100%;
  height: auto;
}

/* 视频自适应 */
.wangeditor iframe {
  width: 100%;
  height: 400px;
}
</style>
